import Taro from '@tarojs/taro'
import http from '@utils/http'
import { getPayData } from '@api/api'

const getPay = () => {
  return new Promise((resolve, reject) => {
    getPayData().then(data => {
      const { pid, appId, riskType, userId, mobileNo } = data
      my.ap.nsf({
        pid,
        appId,
        bizContext: {
          risk_type: riskType,
          user_id: userId,
          mobile_no: mobileNo,
          pid,
        },
        success: ({ riskResult }) => {
          const params = {
            riskResult: JSON.parse(riskResult) ? JSON.parse(riskResult).riskinfo_nsf_common : '',
          }
          resolve(params)
        },
      })
    })
  })
}

const toPay = (id, type = 1) => {
  return new Promise((resolve, reject) => {
    http.request({
      url: '/order/getOrderStr.json',
      data: {
        id,
        type
      }
    }, true).then(({ data }) => {
      my.tradePay({
        // 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
        orderStr: data,
        success: ({ resultCode }) => {
          resolve(resultCode)
        },
        fail: (err) => reject(err)
      });
    }).catch(err => {
      reject(err)
    })
  })
}

export default {
  getPay,
  toPay
}
